package serverService;

import common.*;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lhn
 * @date 2024-05-07 15:56
 * 服务器监听9999等待连接
 */

public class Server {
    private ServerSocket serverSocket = null;
    //创建集合，存放多个用户，如果是这些用户登录就认为是合法的
    //ConcurrentHashMap可以处理并发的集合，并且线程安全
    public static ConcurrentHashMap<String, User> userHashMap = new ConcurrentHashMap<>();
    static {
        //初始化放入用户数据以模拟数据库
        userHashMap.put("100",new User("100","123456"));
        userHashMap.put("200",new User("200","123456"));
        userHashMap.put("300",new User("300","654321"));
    }
    private  boolean checkUser(User user) {
        User user1 = userHashMap.get(user.getUserId());
        if ( user1!= null ) {
            if (user1.getPassword().equals(user.getPassword())) {
                return true;
            }
        }
        return false;
    }
    public Server() {
        try {
            System.out.println("服务端在端口9999等待连接...");
            //启动推送新闻的线程
            new Thread(new SendNewsToAllService()).start();
            serverSocket = new ServerSocket(9999);

            while (true) {
                Socket socket = serverSocket.accept();
                //得到socket对象的输入流
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                User user = (User) objectInputStream.readObject();  //读取客户端发送的user对象
                Message message = new Message();    //创建Message对象用于回复客户端
                //验证
                if (checkUser(user)) {
                    //合法用户
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    objectOutputStream.writeObject(message);
                    //创建一个线程，和客户端保持通讯
                    ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, user.getUserId());
                    serverConnectClientThread.start();  //启动线程
                    //将线程放入线程集合方便管理
                    ManageServerConnectClientThread.addServerConnectClientThread(user.getUserId(), serverConnectClientThread);

                    //查询是否有离线留言未接收
                    ArrayList<Message> offlineMsgArr = ManageServerConnectClientThread.getOfflineMsgArr(user.getUserId());
                    if (offlineMsgArr != null) {

                        for (Message msg: offlineMsgArr
                             ) {
                            ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(
                                    ManageServerConnectClientThread.getServerConnectClientThread(user.getUserId()).getSocket().getOutputStream()
                            );
                            objectOutputStream1.writeObject(msg);
                        }
                        ManageServerConnectClientThread.removeOfflineMsgArr(user.getUserId());
                        System.out.println("用户" + user.getUserId() + "已获取离线消息");
                    }

                    //查询是否有离线文件未接收
                    ArrayList<Message> offlineFileArr = ManageServerConnectClientThread.getOfflineFileArr(user.getUserId());
                    if (offlineFileArr != null) {

                        for (Message fileMsg: offlineFileArr
                        ) {
                            ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(
                                    ManageServerConnectClientThread.getServerConnectClientThread(user.getUserId()).getSocket().getOutputStream()
                            );
                            objectOutputStream1.writeObject(fileMsg);
                        }
                        ManageServerConnectClientThread.removeOfflineFileArr(user.getUserId());
                        System.out.println("用户" + user.getUserId() + "已获取离线文件");
                    }


                } else {
                    //非法用户
                    System.out.println("用户id = " + user.getUserId() + "登录失败,用户密码" + user.getPassword());
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    objectOutputStream.writeObject(message);
                    socket.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}